package com.wangxiaonan.wxwork.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.domain.Agent;
import com.wangxiaonan.wxwork.domain.AgentCriteria;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.repository.AgentDao;
import com.wangxiaonan.wxwork.service.AgentService;
import com.wangxiaonan.wxwork.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class AgentServiceImpl implements AgentService {
    private static final Logger logger = LoggerFactory.getLogger(AgentServiceImpl.class);

    @Resource
    private AgentDao agentDao;

    @Override
    public JSONObject getAgent(String token, String agentId) {
        if (StringUtils.isBlank(token) || StringUtils.isBlank(agentId)) {
            logger.error("[TokenServiceImpl] getAgent >> token: {}, agentId: {}", token, agentId);
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        String result;
        try {
            String url = String.format(AgentService.DEFAULT_GET_AGENT_GET_URL, token, agentId);
            result = HttpUtil.get(url);
        } catch (IOException e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[AgentServiceImpl] getAgent >> result: {}", result);
            throw new ClassCastException("请求结果格式化错误");
        }

        return json;
    }

    @Override
    public JSONObject setAgent(String token, String jsonParam) {
        if (StringUtils.isBlank(token)) {
            logger.error("[TokenServiceImpl] setAgent >> token: {}", token);
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        String result;
        try {
            String url = String.format(AgentService.DEFAULT_POST_AGENT_SET_URL, token);
            result = HttpUtil.post(url, jsonParam);
        } catch (IOException e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[AgentServiceImpl] setAgent >> result: {}", result);
            throw new ClassCastException("请求结果格式化错误");
        }

        return json;
    }

    @Override
    public JSONObject getAgentList(String token) {
        if (StringUtils.isBlank(token)) {
            logger.error("[TokenServiceImpl] setAgent >> token: {}", token);
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }
        String result;
        try {
            String url = String.format(AgentService.DEFAULT_GET_AGENT_LIST_URL, token);
            result = HttpUtil.get(url);
        } catch (IOException e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject json;
        try {
            json = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[AgentServiceImpl] getAgentList >> result: {}", result);
            throw new ClassCastException("请求结果格式化错误");
        }

        return json;
    }

    @Override
    public Agent queryAgentById(String agentId) {
        if (StringUtils.isBlank(agentId)) {
            logger.error("[TokenServiceImpl] getAgentById >> agentId is null");
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }

        return agentDao.selectByPrimaryKey(agentId);
    }

    @Override
    public List<Agent> queryAgentList(Integer limitStart, Integer pageSize) {
        AgentCriteria ac = new AgentCriteria();
        if (limitStart != null) {
            ac.setLimitStart(limitStart);
        }
        if (pageSize != null) {
            ac.setPageSize(pageSize);
        }

        return agentDao.selectByCriteria(ac);
    }

    @Override
    public int saveAgent(Agent agent) {
        if (agent == null || StringUtils.isBlank(agent.getAgentId())
                || StringUtils.isBlank(agent.getCorpId())
                || StringUtils.isBlank(agent.getSecret())) {
            logger.error("[TokenServiceImpl] getAgentById >> agentId is invalid");
            throw new ServiceException("param_invalid", "请求参数不能为空");
        }

        return agentDao.insert(agent);
    }
}
